package com.example.mvvmcore.viewmodel;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.lifecycle.ViewModel;

import com.example.mvvmcore.repository.BaseRepository;


public abstract class BaseViewModel<Repo extends BaseRepository> extends ViewModel implements LifecycleObserver {
    protected Repo mRepository;

    public BaseViewModel(LifecycleOwner _owner){
        mRepository=createRepository();
        _owner.getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void activityOnCreate(){
        initResource();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void activityOnStop(){
        releaseResource();
    }
    /**
     * 释放资源
     */
    protected abstract void releaseResource();
    /**
     * 初始化资源
     */
    protected abstract void initResource();
    /**
     * 创建数据仓库实例
     * @return
     */
    protected abstract Repo createRepository();
}
